<template>
  <div
    class="app-container"
    style="height: 100%"
    v-loading="loadingSave"
    element-loading-text="加载中..."
  >
    <div style="padding-bottom: 12px" class="">
      <div class="header flex-justify-between">
        <span class="title_tip">{{ route.params.id ? '编辑商家' : '新建商家' }}</span>
        <div class="footer_btn_save">
          <HPlainButton @focus="btnCancelFocus" @click="addSave">保存</HPlainButton>
          <HButton @click="onBack"> 取消 </HButton>
        </div>
      </div>
    </div>
    <div class="app-container-inner" style="display: flex; flex-direction: column; flex: 1">
      <!-- 创建网点 -->
      <div class="create-work">
        <el-form
          label-position="right"
          ref="formRef"
          :model="data"
          require-asterisk-position="left"
          :rules="rules"
          label-width="85"
        >
          <h3 class="title">商家信息</h3>
          <section class="basic_information">
            <ul class="left_info">
              <li>
                <el-form-item label="商家名称" prop="name">
                  <span class="flex_item">
                    <el-input placeholder="请输入商家名称" v-model="data.name" clearable />
                  </span>
                </el-form-item>

                <!-- 绑定账号 -->
                <el-form-item label="绑定账号" prop="accountPhone">
                  <span class="flex_item">
                    <el-input
                      v-model="data.accountPhone"
                      maxlength="11"
                      clearable
                      placeholder="请输入绑定的手机号"
                      @keyup="handleInputOnlyNumber"
                    />
                    <el-button
                      type="primary"
                      class="ma_left"
                      color="#007cff"
                      round
                      size="small"
                      :loading="getResponsiblePersonalLoading"
                      @focus="btnCancelFocus"
                      @click="empPageSelecctList(data.accountPhone)"
                      >获取</el-button
                    >
                  </span>
                </el-form-item>

                <!-- 负责人员 -->
                <el-form-item label="负责人员" prop="accountName">
                  <span class="flex_item">
                    <el-input
                      :disabled="isInput"
                      v-model="data.accountName"
                      clearable
                      placeholder="根据绑定手机号获取"
                    />
                    <el-tooltip effect="light" content="获取不到则手动输入！" placement="right">
                      <el-icon size="18" class="ma_left" color="#ff5733">
                        <Warning />
                      </el-icon>
                    </el-tooltip>
                  </span>
                </el-form-item>
                <el-form-item label="工单策略">
                  <el-button
                    type="primary"
                    color="#007cff"
                    size="small"
                    round
                    @click="updateStrategyVisible = true"
                  >
                    前往编辑策略
                    <el-icon class="icon_right" color="#007cff" size="14">
                      <Right />
                    </el-icon>
                  </el-button>
                </el-form-item>
                <el-form-item label="结算类型">
                  <el-radio-group v-model="data.strategy.settlementType">
                    <el-radio :value="1">预充值</el-radio>
                    <el-radio :value="2">月结</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="商家状态">
                  <el-radio-group v-model="data.status">
                    <el-radio :value="2">启用</el-radio>
                    <el-radio :value="4">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </li>
              <li>
                <el-form-item label="联系人" prop="username">
                  <el-input placeholder="请输入联系人" v-model="data.username" clearable />
                </el-form-item>
                <el-form-item label="联系人电话" prop="phone">
                  <el-input
                    v-model="data.phone"
                    maxlength="11"
                    clearable
                    placeholder="联系人电话"
                    @keyup="handleInputOnlyNumber"
                  />
                </el-form-item>
                <el-form-item required label="服务商地址" prop="province">
                  <SingleAddress
                    ref="addrsDom"
                    :address="addrs"
                    class="addrsDom_"
                    @value-change="addressValChange"
                  />
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                  <el-input
                    v-model="data.address"
                    :autosize="{ minRows: 1, maxRows: 4 }"
                    type="textarea"
                    maxlength="200"
                    show-word-limit
                    placeholder="请输入详细地址"
                    clearable
                  />
                </el-form-item>
                <!-- 暂时隐藏以后可能会用到 -->
                <!-- <el-form-item label="单号标识码" prop="orderIdentifierNo">
                  <span class="flex_item">
                    <el-input
                      :disabled="!!route.params.id"
                      v-model="data.orderIdentifierNo"
                      clearable
                      placeholder="请输入单号标识码"
                    />
                    <el-tooltip
                      effect="light"
                      content="创建后不可修改，该标识会在工单单号或其他相关单号中使用！"
                      placement="right"
                    >
                      <el-icon size="18" class="ma_left" color="#ff5733">
                        <Warning />
                      </el-icon>
                    </el-tooltip>
                  </span>
                </el-form-item> -->
              </li>
            </ul>
          </section>
          <h3 class="title">商家结算</h3>
          <section class="table_list">
            <el-table
              height="100%"
              style="position: absolute"
              :data="data.moduleSettlements"
              :border="true"
              stripe
              resizable
            >
              <template #empty>
                <el-empty description="暂无数据" :image-size="140" />
              </template>
              <el-table-column label="序号" width="70" fixed>
                <template v-slot="scope">
                  <span class="order"> {{ scope.$index + 1 }} </span>
                  <span class="add_delete">
                    <el-icon size="16" color="#007cff" class="add" @click="onAddItem">
                      <CirclePlus />
                    </el-icon>
                    <el-icon
                      color="rgba(245, 108, 108, 1)"
                      size="16"
                      @click="detelePri(scope.row, scope.$index)"
                    >
                      <Delete />
                    </el-icon>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                label="工单类型"
                prop="name"
                min-width="200"
                align="center"
              >
                <template #default="scope">
                  <el-select
                    placeholder="请选择模块"
                    filterable
                    clearable
                    v-model="scope.row.moduleId"
                    :filter-method="getWorkModulePriceOptions"
                    :loading="loading"
                    remote-show-suffix
                  >
                    <el-option
                      v-for="item in workModulePriceOptions"
                      :key="item.name"
                      :disabled="isStop(item.id)"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                label="模块默认费用"
                min-width="120"
                align="center"
              >
                <template v-slot="item">
                  <el-input
                    :value="
                      item.row.moduleId
                        ? workModulePriceOptions?.filter((o) => item.row.moduleId == o.id)[0]?.price
                        : ''
                    "
                    disabled
                    class="height_28"
                  >
                    <template #prepend>￥</template></el-input
                  >
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip label="结算模式" min-width="80" align="center">
                <template v-slot="item">
                  <div
                    style="display: flex; align-items: center; gap: 5px; justify-content: center"
                  >
                    <el-switch v-model="item.row.allInclusiveFee" inline-prompt />
                    <span>{{ item.row.allInclusiveFee ? '费用全包' : '仅含下单费' }}</span>
                    <el-tooltip
                      v-if="item.row.allInclusiveFee"
                      content="全包：配件费 + 服务费"
                      effect="light"
                      placement="right"
                    >
                      <el-icon size="18" class="ma_left" color="#ff5733">
                        <Warning />
                      </el-icon>
                    </el-tooltip>
                  </div>
                </template>
                <template #header>
                  结算模式
                  <el-popover placement="top-start" ref="popover" trigger="click" :width="160">
                    <h5 style="margin-bottom: 10px">批量填充结算模式</h5>
                    <div
                      style="display: flex; align-items: center; justify-content: center; gap: 5px"
                    >
                      <el-switch v-model="AllType" inline-prompt />
                      <span style="white-space: nowrap">
                        {{ AllType ? '费用全包' : '仅含下单费' }}
                      </span>
                      <el-tooltip
                        v-if="AllType"
                        content="全包：配件费 + 服务费"
                        effect="light"
                        placement="right"
                      >
                        <el-icon size="18" class="ma_left" color="#ff5733">
                          <Warning />
                        </el-icon>
                      </el-tooltip>
                    </div>
                    <div style="display: flex; justify-content: end; margin-top: 10px">
                      <el-button
                        color="#007cff"
                        style="padding: 0 4px; height: 20px"
                        @click="changeAllType"
                        >确定</el-button
                      >
                    </div>
                    <template #reference>
                      <span class="multiple_btn">批量</span>
                    </template>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column
                prop="qty"
                show-overflow-tooltip
                label="商家结算价"
                min-width="140"
                align="center"
              >
                <template #header>
                  商家结算价
                  <el-popover placement="top-start" ref="popover2" trigger="click" :width="160">
                    <h5 style="margin-bottom: 10px">批量填充数量</h5>
                    <el-input
                      placeholder="请输入"
                      v-model="Allprice"
                      @input="Allprice = Allprice.replace(/[^0-9]/g, '')"
                      @keyup.enter="changeAllAllprice"
                    />
                    <div style="display: flex; justify-content: end; margin-top: 10px">
                      <el-button
                        color="#007cff"
                        style="padding: 0 4px; height: 20px"
                        @click="changeAllAllprice"
                        >确定</el-button
                      >
                    </div>
                    <template #reference>
                      <span class="multiple_btn">批量</span>
                    </template>
                  </el-popover>
                </template>
                <template v-slot="item">
                  <el-input
                    v-model="item.row.price"
                    placeholder="结算价"
                    :formatter="(value) => `${value}`.replace(/[^\d]/g, '')"
                    :parser="(value) => value.replace(/[^\d]/g, '')"
                    class="height_28"
                  >
                    <template #prepend>￥</template></el-input
                  >
                </template>
              </el-table-column>
            </el-table>
          </section>
        </el-form>
      </div>
    </div>

    <!--策略编辑弹窗-->
    <UpdateStrategy
      :modal-visible="updateStrategyVisible"
      @update="handleUpdateStrategy"
      @close="updateStrategyVisible = false"
      :strategy="data.strategy"
    />
  </div>
</template>

<script setup lang="ts">
  import SingleAddress from '@/components/address/singleAddress.vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ref, reactive, onMounted, watch } from 'vue'
  import { getBeforeUpdateSelect, factorySave } from '@/api/merchant'
  import { getFactoryAccountByPhone } from '@/api/organize'
  import { workModulePricePageSelect } from '@/api/order'
  import { ElMessage, FormInstance } from 'element-plus'
  import { phone, verifyPhone, setProvince } from '@/utils/validate'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import * as _ from 'lodash'
  import { CirclePlus, Delete, Right, Warning } from '@element-plus/icons-vue'
  import UpdateStrategy from './components/UpdateStrategy.vue'
  import { Strategy } from '../list/components/EditStrategyBtn/types'
  import { WorkModulePriceOption } from './types'
  import HButton from '@/components/common/button/HButton.vue'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.merchant.merchantForm,
  })

  // 工单模块带费用下拉选项
  const workModulePriceOptions = ref<Array<WorkModulePriceOption>>([])

  /**
   * 获取工单模块带费用下拉选项
   * @param {string} query 关键字
   */
  const getWorkModulePriceOptions = _.throttle((query: string) => {
    loading.value = true
    const param = {
      limit: 0,
      name: query,
      page: 0,
    }
    workModulePricePageSelect(param).then((res) => {
      workModulePriceOptions.value = res.data.data.rows
      loading.value = false
    })
  }, 500)

  /**
   * 新增模块费用
   */
  const onAddItem = async () => {
    data.value.moduleSettlements.push({
      id: null,
      moduleId: null, //	模块ID
      price: null, // 结算价
      allInclusiveFee: false, // 是否全包费用(配件费+服务费)：false-不包含，true-包含
    })
  }

  /**
   * 验证工单模块带费用下拉选项是否可选
   * @param {string} id 工单模块带费用id
   */
  const isStop = (id: string) => {
    let arr: Array<string> = []
    arr = data.value.moduleSettlements.map((o) => {
      return o.moduleId
    })
    return arr.includes(id)
  }

  // 修改费用标准
  const TagsViewStore = useTagsViewStore()
  const popover = ref()
  const popover2 = ref()
  const addrsDom = ref()

  // 表单组件实例
  const formRef = ref<FormInstance>()

  // 全局路由对象
  const router = useRouter()

  // 激活的路由对象
  const route = useRoute()

  const loadingSave = ref(false)
  let loading = ref(false)
  const isInput = ref(true)
  let addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })
  let data: any = ref({
    accountId: null, //品牌商家账号ID
    phone: '', //	联系人电话
    accountName: '', //服务商负责人名称
    accountPhone: '', //	绑定账号(手机号)
    address: '',
    area: '',
    province: '',
    city: '',
    town: '',
    // orderIdentifierNo: '', 暂时先不要
    username: '', //	联系人名称
    delModuleSettlementIds: [], //删除的服务模块结算对象ID
    id: null, //商家ID，新增不必传，修改必传
    moduleSettlements: [], //服务模块结算对象
    name: '', //商家名称
    status: 2, //	商家状态：false-启用，true-禁用
    strategy: {
      //品牌商家策略对象
      enableApplyFee: false, //是否开启申请工单费用：false-不开启，true-开启，当enableFeeAuthori=true时生效
      enableApplySpare: false, //是否开启申请工单配件：false-不开启，true-开启，当enableSpareAuthori=true时生效
      enableCheckFee: false, //	是否开启审核工单费用：false-不开启，true-开启，当enableFeeAuthori=true时生效
      enableCheckSpare: false, //是否开启审核工单配件：false-不开启，true-开启，当enableSpareAuthori=true时生效
      enableFeeAuthori: false, //是否开启工单费用权限：false-不开启，true-开启
      enableSpareAuthori: false, //	是否开启工单配件权限：false-不开启，true-开启
      orderBalanceStrategy: 1, // 报单余额策略: 1-不限制/余额不足亦可下单，2-余额不足禁止下单
      settlementType: 1, // 结算类型：1-预充值，2-月结
    },
  })

  const rules = reactive({
    accountPhone: [
      { required: true, message: '请输入绑定的手机号', trigger: 'blur' },
      { validator: phone(data.value.phone), trigger: 'blur' },
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: phone(data.value.phone), trigger: 'blur' },
    ],
    name: [
      { required: true, message: '请输入商家名称', trigger: 'blur' },
      { max: 20, message: '长度不超过20个字符', trigger: 'blur' },
    ],
    username: [
      { required: true, message: '请输入联系人名称', trigger: 'blur' },
      { max: 20, message: '长度不超过20个字符', trigger: 'blur' },
      { min: 2, message: '长度小于2个字符', trigger: 'blur' },
    ],
    accountName: [{ required: true, message: '请输入负责人名称', trigger: ['change', 'blur'] }],
    province: [{ validator: setProvince(data.value.province), trigger: 'change' }],
    address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
    // orderIdentifierNo: [{ required: true, message: '请输入单号标识号', trigger: 'blur' }],
  })

  // 获取负责人员加载
  const getResponsiblePersonalLoading = ref(false)

  // 获取负责人员
  const empPageSelecctList = _.debounce((val) => {
    if (!verifyPhone(val)) {
      ElMessage({
        showClose: true,
        message: '手机号码格式不正确，请重新输入',
        type: 'warning',
      })
      return
    }
    getResponsiblePersonalLoading.value = true
    // 获取负责人信息
    getFactoryAccountByPhone(val).then((res) => {
      if (res.data.success) {
        if (res.data.data.row.existPhone) {
          data.value.accountId = res.data.data.row.id
          data.value.accountName = res.data.data.row.username
          data.value.accountPhone = res.data.data.row.phone
          ElMessage({
            showClose: true,
            message: '获取成功',
            type: 'success',
          })
        } else {
          data.value.accountName = ''
          data.value.accountId = null
          isInput.value = false
          ElMessage({
            showClose: true,
            message: '获取不到，请手动输入！',
            type: 'warning',
          })
        }
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
          })
      }
      getResponsiblePersonalLoading.value = false
    })
  }, 500)

  // 删除模块费用
  const detelePri = (row, index) => {
    data.value.moduleSettlements = data.value.moduleSettlements.filter((o, index1) => {
      return index1 != index
    })
    if (row.id) {
      data.value.delModuleSettlementIds.push(row.id)
    }
  }
  // 批量填写
  const Allprice = ref()
  const changeAllAllprice = () => {
    if (data.value.moduleSettlements.length == 0) return
    data.value.moduleSettlements = data.value.moduleSettlements.map((o) => {
      return { ...o, price: Allprice.value }
    })
    popover2.value.hide()
  }
  // 批量填写
  const AllType = ref(false)
  const changeAllType = () => {
    if (data.value.moduleSettlements.length == 0) return
    data.value.moduleSettlements = data.value.moduleSettlements.map((o) => {
      return { ...o, allInclusiveFee: AllType.value }
    })
    AllType.value = false
    popover.value.hide()
  }

  // 初始化data
  const initData = () => {
    data.value = {
      accountId: null, //品牌商家账号ID
      phone: '', //	联系人电话
      accountName: '', //服务商负责人名称
      accountPhone: '', //	绑定账号(手机号)
      address: '',
      area: '',
      province: '',
      city: '',
      town: '',
      // orderIdentifierNo: '',
      username: '', //	联系人名称
      delModuleSettlementIds: [], //删除的服务模块结算对象ID
      id: null, //商家ID，新增不必传，修改必传
      moduleSettlements: [], //服务模块结算对象
      name: '', //商家名称
      status: 2, //	商家状态：false-启用，true-禁用
      strategy: {
        //品牌商家策略对象
        enableApplyFee: false, //是否开启申请工单费用：false-不开启，true-开启，当enableFeeAuthori=true时生效
        enableApplySpare: false, //是否开启申请工单配件：false-不开启，true-开启，当enableSpareAuthori=true时生效
        enableCheckFee: false, //	是否开启审核工单费用：false-不开启，true-开启，当enableFeeAuthori=true时生效
        enableCheckSpare: false, //是否开启审核工单配件：false-不开启，true-开启，当enableSpareAuthori=true时生效
        enableFeeAuthori: false, //是否开启工单费用权限：false-不开启，true-开启
        enableSpareAuthori: false, //	是否开启工单配件权限：false-不开启，true-开启
        orderBalanceStrategy: 1, // 报单余额策略: 1-不限制/余额不足亦可下单，2-余额不足禁止下单
        settlementType: 1, // 结算类型：1-预充值，2-月结
      },
    }
  }

  // 保存
  async function addSave() {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      let dataSave = _.cloneDeep(data.value)
      loadingSave.value = true
      const __moduleSettlements = []
      dataSave.moduleSettlements.forEach((item) => {
        if (item.moduleId) {
          __moduleSettlements.push(item)
        }
      })
      dataSave.moduleSettlements = __moduleSettlements
      const res = await factorySave(dataSave)
      if (res.data.success) {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'success',
        })
        router.push('/merchant/list')
        // refresh()
        TagsViewStore.delView(router.currentRoute.value.path)

        // 解决添加后再次添加表单会保留上一次填写的信息
        if (!route.params.id) {
          initData()
          formRef.value.resetFields()
        }
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
          })
      }
      loadingSave.value = false
    } catch (e) {
      // 校验不通过
    }
  }
  // 所属地址
  function addressValChange() {
    const addr = addrsDom.value.getSelectAddr()
    data.value.province = addr.province
    data.value.city = addr.city
    data.value.area = addr.area
    data.value.town = addr.town
  }
  // 获取新增后的详情
  async function getBeforeNetworkEditSelectData(id) {
    loadingSave.value = true
    if (route.params.id) {
      const res = await getBeforeUpdateSelect(id)
      if (res.data.success) {
        let row = res.data.data.row
        data.value = { ...row }
        data.value.delModuleSettlementIds = [] //删除的服务模块结算对象ID
        if (row.moduleSettlements.length == 0) {
          onAddItem()
        } else {
          getWorkModulePriceOptions('')
        }
        addrs.value = {
          // 地址
          province: row.province,
          city: row.city,
          area: row.area,
          town: row.town,
        }
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
          })
      }
    }
    loadingSave.value = false
  }

  // 取消
  const onBack = () => {
    if (!formRef.value) return
    formRef.value.resetFields()
    router.back()
  }

  // 按钮取消聚焦
  const btnCancelFocus = (e: Event) => {
    ;(e.target as HTMLButtonElement).blur()
  }

  // 策略编辑弹窗状态
  const updateStrategyVisible = ref(false)

  // 策略编辑弹窗确认事件
  const handleUpdateStrategy = (strategy: Strategy) => {
    Object.assign(data.value.strategy, { ...strategy })
    updateStrategyVisible.value = false
  }

  /**
   * 电话输入事件
   * 限制输入框只能输入数字
   * @param {Event} e 键盘按下事件
   */
  const handleInputOnlyNumber = (e: Event) => {
    ;(e.target as HTMLInputElement).value = (e.target as HTMLInputElement).value.replace(
      /[^\d]/g,
      '',
    )
  }

  // 解决多次编辑时会出现数据不显示的问题
  watch(
    () => route.name,
    (value) => {
      if (value === 'newDetail' && route.params.id) {
        getBeforeNetworkEditSelectData(route.params.id)
      }
    },
  )

  onMounted(async () => {
    if (route.params.id) {
      await getBeforeNetworkEditSelectData(route.params.id)
    } else {
      onAddItem()
    }
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
